package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/3/17 16:04
 * @Version 1.0
 */

@DubboService
public class MovementServiceImpl implements MovementService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisIdService redisIdService;


    @Autowired
    private MovementAsyncService movementAsyncService;

    @Override
    public void saveMovement(Movement movement) {

        //0.redis主键自增
        Long pid = redisIdService.getNextId(ConstantUtil.MOVEMENT_ID);
        movement.setPid(pid);//大数据需要的id

        //1.保存动态详情
        mongoTemplate.save(movement);

        //2.调用新线程保存好友（异步）
        movementAsyncService.saveMovementFriend(movement);


    }

    @Override
    public PageBeanVo findMyMoveMentByPage(Long userId, Integer pageNum, Integer pageSize) {

        //1.构建查询条件
        Integer index = (pageNum - 1) * pageSize;

        //条件
        Query query = new Query(
                Criteria.where("userId").is(userId)
                        .and("state").is(1)
        ).with(Sort.by(Sort.Order.desc("created")))
                .skip(index).limit(pageSize);

        //2.查询动态详情
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        //3.查询总记录数
        long count = mongoTemplate.count(query, Movement.class);

        //4.封装并返回分页对象
        return new PageBeanVo(pageNum, pageSize, count, movementList);

    }

    @Override
    public PageBeanVo findFriendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.构建分页条件
        Integer index = (pageNum - 1) * pageSize;
        //2.查询好友动态列表
        Query query = new Query(
                //Criteria.where("").and("state").is(1)
        ).with(Sort.by(Sort.Order.desc("created")))
                .skip(index).limit(pageSize);
        //遍历好友动态列表查询动态详情
        List<FriendMovement> friendMovementList = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);
        //创建集合
        List<Movement> movementList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(friendMovementList)) {

            for (FriendMovement friendMovement : friendMovementList) {

                ObjectId publishId = friendMovement.getPublishId();
                //查询动态详情
                Movement movement = mongoTemplate.findById(publishId, Movement.class);

                //判断动态状态,添加到集合中
                if (movement.getState() == 1) {
                    movementList.add(movement);
                }


            }

        }
        //返回并封装pageBeanVo
        return new PageBeanVo(pageNum, pageSize, 0L, movementList);


    }

    @Override
    public PageBeanVo findRecommendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 查询推荐动态
        Integer index = (pageNum - 1) * pageSize;
        // 1.构建条件
        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).with(Sort.by(Sort.Order.desc("created")))
                .skip(index).limit(pageSize);

        // 2.查询推荐动态列表
        List<RecommendMovement> recommendMovementList = mongoTemplate.find(query, RecommendMovement.class);

        // 3.遍历
        List<Movement> movementList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(recommendMovementList)) {

            for (RecommendMovement recommendMovement : recommendMovementList) {

                // 根据推荐动态id查询动态详情
                ObjectId publishId = recommendMovement.getPublishId();

                Movement movement = mongoTemplate.findById(publishId, Movement.class);

                if (movement.getState() == 1) {

                    // 添加到集合
                    movementList.add(movement);

                }

            }


        }

        // 4.返回并封装pageBeanVo
        return new PageBeanVo(pageNum, pageSize, 0L, movementList);


    }

    @Override
    public Movement findById(ObjectId objectId) {

        return mongoTemplate.findById(objectId, Movement.class);

    }

    @Override
    public PageBeanVo findMovementByPage(Long userId, Integer state, Integer pageNum, Integer pageSize) {

        //1.分页条件
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum - 1) * pageSize).limit(pageSize);

        //动态条件
        if (userId != null) {

            query.addCriteria(Criteria.where("userId").is(userId));

        }
        if (state != null) {

            query.addCriteria(Criteria.where("state").is(state));

        }

        //查询list
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        //2.查记录数条件
        Query queryCount = new Query()
                .with(Sort.by(Sort.Order.desc("created")));

        //动态条件
        if (userId != null) {

            queryCount.addCriteria(Criteria.where("userId").is(userId));

        }
        if (state != null) {

            queryCount.addCriteria(Criteria.where("state").is(state));

        }

        //查询记录数
        long counts = mongoTemplate.count(queryCount, Movement.class);

        //3.返回封装分页对象
        return new PageBeanVo(pageNum, pageSize, counts, movementList);

    }

    @Override
    public void update(Movement movement) {

        mongoTemplate.save(movement);

    }
}
